package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.task.AppTokenHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class PrivilegeFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties prop;

    @Autowired
    private AppTokenHolder tokenHolder;  // 这个对象中已经保存了申请好的token

    /**
     * 在请求头中加入App自己的token
     * @param exchange      用于获取请求数据
     * @param chain         过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 往请求头中添加token信息
        ServerHttpRequest request = exchange.getRequest().mutate().header(prop.getApp().getHeaderName(), tokenHolder.getToken()).build();
        // 放入交换机中
        ServerWebExchange newExchange = exchange.mutate().request(request).build();
        // 放行
        return chain.filter(newExchange);
    }

    /**
     * 如果有多个过滤器，这个数字越小，越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 6;
    }
}
